package com.zwk.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zwk.gulimall.product.event.AttrEvent;
import com.zwk.gulimall.product.vo.AttrVo;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zwk.common.utils.PageUtils;
import com.zwk.common.utils.Query;

import com.zwk.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.zwk.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.zwk.gulimall.product.service.AttrAttrgroupRelationService;


@Service("attrAttrgroupRelationService")
public class AttrAttrgroupRelationServiceImpl extends ServiceImpl<AttrAttrgroupRelationDao, AttrAttrgroupRelationEntity> implements AttrAttrgroupRelationService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrAttrgroupRelationEntity> page = this.page(
                new Query<AttrAttrgroupRelationEntity>().getPage(params),
                new QueryWrapper<AttrAttrgroupRelationEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void updateRelation(AttrEvent event) {
        AttrVo attrVo=(AttrVo) event.getSource();
        LambdaUpdateWrapper<AttrAttrgroupRelationEntity> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AttrAttrgroupRelationEntity::getAttrId,attrVo.getAttrId());
        if (attrVo.getAttrGroupId()==null){
            this.remove(wrapper);
            return;
        }
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrId(attrVo.getAttrId());
        relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
        int count = this.count(wrapper);
        if (count<=0){
            this.save(relationEntity);
        }else {
            this.update(relationEntity,wrapper);
        }
    }

    @Override
    public boolean saveRelation(AttrEvent event) {
        AttrVo attrVo=(AttrVo) event.getSource();
        if (attrVo.getAttrId()==null||attrVo.getAttrGroupId()==null){
            return false;
        }
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
        relationEntity.setAttrId(attrVo.getAttrId());
        return this.save(relationEntity);
    }

    @Override
    public boolean removeRelationByAttr(AttrEvent event) {
        AttrVo attrVo = (AttrVo) event.getSource();
        return this.remove(new LambdaUpdateWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId,attrVo.getAttrId()));
    }

}